package com.etime.shyauth.controller;

import com.etime.shyauth.config.BaseMessage;
import com.etime.shyauth.config.ListMessage;
import com.etime.shyauth.config.PojoMessage;
import com.etime.shyauth.config.Tools;
import com.etime.shyauth.dto.CurrentUser;
import com.etime.shyauth.pojo.SysFunction;
import com.etime.shyauth.services.interfaces.CurrentUserService;
import com.etime.shyauth.services.interfaces.SysUserService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 获取当前登录用户的controller
 */
@RestController
@Api(tags = "获取当前登录用户的数据接口。需要通过token参数进行获取")
@RequestMapping("/auth")
public class CurrentUserController {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private Tools tools;
    @Autowired
    private CurrentUserService currentUserService;
    @Autowired
    private SysUserService sysUserService;

    @ApiOperation("根据token获取当前登录用户的信息；可以不用传递token参数")
    @ApiImplicitParam("用户的token，可以不用传递。但是必须要在请求头中有token属性")
    @GetMapping("/current")
    public PojoMessage<CurrentUser> getCurrentUser(String token, HttpServletRequest request){
        if(token==null || token.equals("")){
            token = request.getHeader("token");
        }
        PojoMessage<CurrentUser> msg = new PojoMessage<>();
        CurrentUser user = tools.getCurrentUserFromRedis(token);
        if(user!=null){
            msg.setData(user);
            msg.setCode(1);
        }else{
            msg.setCode(-2);
            msg.setMsg("未获取到用户信息；可能登录超时");
        }
        return msg;
    }

    @ApiOperation("获取用户所能使用的功能列表（用于初始化主界面功能列表）")
    @ApiImplicitParam("用户的token,可以不用传递。但是必须要在请求头中有token属性")
    @GetMapping("/initfun")
    public ListMessage<SysFunction> selectLoginUserRight(String token, HttpServletRequest request){
        if(token==null || token.equals("")){
            token = request.getHeader("token");
        }
        ListMessage<SysFunction> msg = new ListMessage<>();
        CurrentUser user = tools.getCurrentUserFromRedis(token);
        if(user!=null){
            List<SysFunction> funlist = currentUserService.selectLoginUserRight(user.getUser().getUserid());
            msg.setCode(1);
            msg.setDatalist(funlist);
        }else{
            msg.setCode(-2);
            msg.setMsg("未获取到用户信息；可能登录超时");
        }
        return msg;
    }


    /**
     * 修改个人用户信息
     * @param currentUser 个人用户信息；
     * @return
     */
    @ApiOperation("修改个人用户信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "user.usertruename",value = "用户姓名"),
            @ApiImplicitParam(name="user.nickname",value="用户昵称"),
            @ApiImplicitParam(name="user.userbirthyear",value="出身年份"),
            @ApiImplicitParam(name="user.userbirthmonth",value="出身月份"),
            @ApiImplicitParam(name="user.userbirthday",value="出身日期"),
            @ApiImplicitParam(name="user.useroccupation",value="用户职业"),
            @ApiImplicitParam(name="user.usermajor",value="专业"),
            @ApiImplicitParam(name="user.userphone",value="联系电话"),
            @ApiImplicitParam(name="user.useremail",value="邮箱"),
            @ApiImplicitParam(name="user.userid",value="用户id"),
            @ApiImplicitParam(name="user.code",value="个性签名")
    })
    @PostMapping("/update")
    public BaseMessage updateCurrentUser(@RequestBody  CurrentUser currentUser){
        BaseMessage msg = new BaseMessage();
        int rtn = sysUserService.updateBaseSysUser(currentUser.getUser());
        msg.setCode(rtn);
        if(rtn>0){
            msg.setMsg("修改用户成功");
            //重新将currentUser写入到redis中
            saveUserToReids(currentUser);
        }else{
            msg.setMsg("修改用户失败");
        }
        return msg;
    }

    /**
     * 保存用户数据到redis中
     * key=token; 使用用户id+用户名+密码混合加密后的结果作为key
     * value=user
     * 保存时间：30min
     *
     * @param user
     * @return 返回需要客户端记录的token；也是记录到redis中的key。
     */
    private String saveUserToReids(CurrentUser user) {
        String key = DigestUtils.md5DigestAsHex(user.getUser().getUserid().toString().getBytes());
        //转换为json格式字符串存储
        ObjectMapper om = new ObjectMapper();
        String str;
        try {
            str = om.writeValueAsString(user);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            str = "";
        }
        stringRedisTemplate.boundValueOps(key).set(str);
        //不过期redis
        //stringRedisTemplate.boundValueOps(key).expire(30, TimeUnit.MINUTES);
        return key;
    }
//    /**
//     * 从redis缓存中获取当前登录的用户
//     * @param token 用户令牌
//     * @return
//     */
//    private CurrentUser getCurrentUserFromRedis(String token){
//        CurrentUser user = null;
//        if(stringRedisTemplate.hasKey(token)){
//            //从reids中获取用户登录信息
//            String str = stringRedisTemplate.boundValueOps(token).get();
//            //重置过期时间
//            stringRedisTemplate.boundValueOps(token).expire(30, TimeUnit.MINUTES);
//            ObjectMapper om = new ObjectMapper();
//            try {
//                user = om.readValue(str,CurrentUser.class);
//            } catch (JsonProcessingException e) {
//                e.printStackTrace();
//                user = null;
//            }
//        }
//        return user;
//    }

}
